<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------


namespace app\common\controller;



use think\Controller;

/**
 * 项目公共控制器
 * @package app\common\controller
 */
class Common extends Controller
{
    /**
     * 顶部按钮组
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public $top_button = [
        ['ident'=> 'add', 'title'=>'新增', 'href'=>'add', 'icon'=>'fa fa-plus pr5','class'=>'btn btn-sm mr5 btn-primary layeradd '],
//        ['ident'=> 'enable', 'title'=>'批量启用','href'=>['setstatus',['type'=>'enable']],'icon'=>'fa fa-check-circle pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
//        ['ident'=> 'disable', 'title'=>'批量禁用','href'=>['setstatus',['type'=>'disable']],'icon'=>'fa fa-ban pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
//        ['ident'=> 'delete', 'title'=>'批量删除','href'=>'delete','icon'=>'fa fa-times pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
    ];

    public $top_button_quick = [
        ['ident'=> 'add', 'title'=>'新增', 'href'=>'add', 'icon'=>'fa fa-plus pr5','class'=>'btn btn-sm mr5 btn-primary quickadd '],
        // ['ident'=> 'enable', 'title'=>'批量启用','href'=>['setstatus',['type'=>'enable']],'icon'=>'fa fa-check-circle pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
        // ['ident'=> 'disable', 'title'=>'批量禁用','href'=>['setstatus',['type'=>'disable']],'icon'=>'fa fa-ban pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
        // ['ident'=> 'delete', 'title'=>'批量删除','href'=>'delete','icon'=>'fa fa-times pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
    ];
    public $top_button_layer = [
        ['ident'=> 'add', 'title'=>'新增', 'href'=>'add', 'icon'=>'fa fa-plus pr5','class'=>'btn btn-sm mr5 btn-primary layeradd '],
        // ['ident'=> 'enable', 'title'=>'批量启用','href'=>['setstatus',['type'=>'enable']],'icon'=>'fa fa-check-circle pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
        // ['ident'=> 'disable', 'title'=>'批量禁用','href'=>['setstatus',['type'=>'disable']],'icon'=>'fa fa-ban pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
        // ['ident'=> 'delete', 'title'=>'批量删除','href'=>'delete','icon'=>'fa fa-times pr5','class'=>'btn btn-sm mr5 btn-default  ajax-post confirm','extra'=>'target-form="ids"'],
    ];
    //底部批量选择操作
    public $bottom_button_select = [
        ['ident' => 'enable', 'title' => '批量启用', 'href' => ['setstatus', ['type' => 'enable']], 'icon' => 'fa fa-check-circle pr5', 'class' => 'btn btn-sm mr5 btn-default  ajax-post confirm', 'extra' => 'target-form="ids"'],
        ['ident' => 'disable', 'title' => '批量禁用', 'href' => ['setstatus', ['type' => 'disable']], 'icon' => 'fa fa-ban pr5', 'class' => 'btn btn-sm mr5 btn-default  ajax-post confirm', 'extra' => 'target-form="ids"'],
        ['ident' => 'delete', 'title' => '批量删除', 'href' => 'delete', 'icon' => 'fa fa-times pr5', 'class' => 'btn btn-sm mr5 btn-default  ajax-post confirm', 'extra' => 'target-form="ids"'],
    ];
    /**
     * 右侧按钮组
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public $right_button = [
        ['ident'=> 'edit', 'title'=>'编辑','href'=>['edit', ['id'=>'__id__', 'layer' => 1]],'icon'=>'fa fa-pencil pr5','class'=>'btn btn-xs mr5 btn-default layeredit'],
        ['ident'=> 'disable', 'title'=>'禁用','href'=>['setstatus',['type'=>'disable','ids'=>'__id__']],'icon'=>'fa fa-ban pr5','class'=>'btn btn-xs mr5 btn-default  ajax-get confirm'],
        ['ident'=> 'delete', 'title'=>'删除','href'=>['delete',['ids'=>'__id__']],'icon'=>'fa fa-times pr5','class'=>'btn btn-xs mr5 btn-default  ajax-get confirm'],
    ];
    
    public $right_button_layer = [
        ['ident'=> 'edit', 'title'=>'编辑','href'=>['edit', ['id'=>'__id__', 'layer' => 1]],'icon'=>'fa fa-pencil pr5','class'=>'btn btn-xs mr5 btn-default layeredit'],
        ['ident'=> 'disable', 'title'=>'禁用','href'=>['setstatus',['type'=>'disable','ids'=>'__id__']],'icon'=>'fa fa-ban pr5','class'=>'btn btn-xs mr5 btn-default  ajax-get confirm'],
        ['ident'=> 'delete', 'title'=>'删除','href'=>['delete',['ids'=>'__id__']],'icon'=>'fa fa-times pr5','class'=>'btn btn-xs mr5 btn-default  ajax-get confirm'],
    ];

    /**
     * 初始化
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    protected function initialize()
    {
        parent::initialize();
        // 模块后台公共模板
        $this->assign('admin_layout', APP_PATH . 'admin/view/layout.html');
        // 输出弹出层参数
        $this->assign('layer', $this->request->param('layer'));
        $this->setPageParam();//修正分页传参
    }

   /**
     * 设置分页参数
     * @author 似水星辰 [2630481389@qq.com]
     */
    final protected function setPageParam()
    {
        $list_rows = input('?param.list_rows') ? input('param.list_rows') : config('list_rows');
        config('paginate.list_rows', $list_rows);
        config('paginate.query', input('get.'));
    }

    /**
     * 获取当前操作模型
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @return object|\think\db\Query
     */
    final protected function getModel()
    {
        $controller  = parse_name($this->request->controller());

        // 使用模型
        try {
            $Model = \App::model($controller);
        } catch (\Exception $e) {
            $this->error('找不到模型：'.$controller);
        }

        return $Model;
    }

    /**
     * 设置状态
     * 禁用、启用、删除都是调用这个内部方法
     * @param string $type 操作类型：enable,disable,delete
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @return mixed
     */
    public function setStatus($type = '')
    {
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids   = (array)$ids;
        $field = input('param.field', 'status');
        if(empty($type)){
            $type = input('param.action');
        }

        empty($ids) && $this->error('缺少主键');

        $Model = $this->getModel();

        $protect_table = [
            '__ADMIN__',
            '__ADMIN_ROLE__',
            '__ADMIN_MODULE__',
            config('database.prefix').'admin',
            config('database.prefix').'admin_role',
            config('database.prefix').'admin_module',
        ];

        // 禁止操作核心表的主要数据
        if (in_array($Model->getTable(), $protect_table) && in_array('1', $ids)) {
            $this->error('禁止操作');
        }

        // 主键名称
        $pk = $Model->getPk();
        $result = false;
        switch ($type) {
            case 'disable': // 禁用
                $result = $Model->where($pk,'IN',$ids)->setField($field, 0);
                break;
            case 'enable': // 启用
                $result = $Model->where($pk,'IN',$ids)->setField($field, 1);
                break;
            case 'delete': // 删除
                $field = $Model->getTableFields($Model->getTable());
                if (in_array('is_del', $field)) {
                    $result = $Model->where($pk, 'IN', $ids)->setField('is_del', 1);
                } else {
                    $result = $Model->where($pk, 'IN', $ids)->delete();
                }

                break;
            default:
                $this->error('非法操作');
                break;
        }

        $table = strtolower(str_replace('__','',$Model->getTable()));

        if (false !== $result) {
            // \Cache::clear();

            // 记录行为
            action_log($table.'_'.$type, $table, $ids, UID, 'ID：'.implode('、', $ids));
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 删除记录
     * @return void
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function delete(){
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids   = (array)$ids;
        if($ids){
            $this->setStatus('delete');
        }

        $this->error('缺少参数');
    }

    /**
     * 设置表单字段数据
     * @param array $fields 字段名集合
     * @param array $info 对应字段值集合
     * @return array
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function setData($fields = [], $info =[]){
        if(is_array($fields)){
            foreach($fields as &$v){
                if($v['type'] != 'sort'){
                    if($v['type'] == 'password'){
                        $v['value'] = '';
                    }else if($v['type'] == 'attr'){
                        $v['value'] = htmlspecialchars_decode($info[$v['name']]);
                    }else{
                        //if($info[$v['name']]){
                            $v['value'] = $info[$v['name']];
                        //}
                    }
                }
            }
        }
        return $fields;
    }
  
    /**
     * 获取筛选条件
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @after 晓风<215628355@qq.com>
     * @param array|string $filter 标识要获取的字段
     * @param array|string $diff 标识要排除的字段
     * @return array
     */
    final protected function getMap($filter = [] ,$diff = [])
    {
        $search_field     = input('param.search_field/s', '');
        $keyword          = input('param.keyword/s', '');
        if($search_field && $keyword ==''){
            $this->error('关键词不能为空');
        }
        // 搜索框搜索
        $map = [];
        if ($search_field != '' && $keyword !== '') {
            $map[] = [$search_field, 'like', "%$keyword%"];
        }
        if(!empty($map)){
            return $map;
        }
        if(!is_array($filter)){
            $filter = explode(",",$filter);
        }
        if(!empty($filter)){
           $param = $this->request->only($filter,'get');
        }else{
           $param = $this->request->get();
        }
        if(!is_array($diff)){
            $diff = explode(",",$diff);
        }
        if(empty($diff)){
            $diff = ["search_field",'keyword','page','list_rows','order','by','export'];
        }       
        
        foreach($param as $k=>$v){
            if($v != "" && !in_array($k,$diff)){
               $map[$k] = $v;
            }         
        }    
        return $map;
    }

    /**
     * 获取字段排序
     * @param string $extra_order 额外的排序字段
     * @param bool $before 额外排序字段是否前置
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @return string
     */
    final protected function getOrder($extra_order = '', $before = false)
    {
        $order = input('param.order/s', '');
        $by    = input('param.by/s', '');
        if ($order == '' || $by == '') {
            return $extra_order;
        }
        if ($extra_order == '') {
            return $order. ' '. $by;
        }
        if ($before) {
            return $extra_order. ',' .$order. ' '. $by;
        } else {
            return $order. ' '. $by . ',' . $extra_order;
        }
    }
}